<!DOCTYPE html>
<html>
<div align="center">
<head>

<font face="Bauhaus 93" color="green" size="6" align="center">
	
	<title>taxiApp</title>
	<link rel="stylesheet" media="screen" href="@{'/public/stylesheets/main.css'}">
	<script src="@{'/public/javascripts/jquery-1.5.min.js'}" type="text/javascript" charset="${_response_encoding}"></script>
	<script type="text/javascript"

		src="http://maps.google.com/maps/api/js?sensor=true"
		src="http://code.jquery.com/jquery-1.8.1.js">
	</script>
	
	<script>
		var yourlocation;
		var marker;
		var provMarker; //marker of provider
		var userMarker; //marker of selected user
		var map;
        var lat = 48.45;//initail coordinates;
        var lng = 34.983333;//initail coordinates;
		var lati;
		var lngi;
		var jsonString = '{"provsList":[{"provId":"10","userId":"20","ULat":"44.9859","ULong":"9.03351","PLat":"45.4839701462306","PLong":"9.190213680267334","id":1},{"provId":"10","userId":"21","ULat":"44.9859","ULong":"9.03351","PLat":"45.475815620095226","PLong":"9.21201467514038","id":2},{"provId":"10","userId":"22","ULat":"44.9859","ULong":"9.03351","PLat":"45.450953584498954","PLong":"9.190127849578857","id":3},{"provId":"10","userId":"23","ULat":"44.9859","ULong":"9.03351","PLat":"45.46636572642042","PLong":"9.188969135284424","id":4}]}';
		var marks = new Array();
		var markers = new Array();//array of all markers;
		var host="localhost";//'192.168.1.9';
		//var host='testmobile.tplinfo.com';
		var port='9000';
		var url='http://'+host+':'+port;//+'/provsRequests?provId=10';

		////
		var lastReceived = 0;
		var end = url+"/provider/end";
	    var exit = url+"/provider/exit";
	    var waitEvents = url+"/provider/waitEvents"; //comet request to server
	    var provAccept = url+"/provider/accept";
	    var lockUser = url+"/provider/lock";
	    var reached = url+"/provider/reached";
	    var declare = url+"/provider/declare";
	    var create = url+"/provider/test/create"; //create and declare new Provider
                    var registration = url+"/Application/provRegistration";
                    var signin = url+"/provider/authentication";
		var userId;
		var provId;

		var greenUser = "@{'/public/images/map/user_green.png'}";
		var greenTaxi = "@{'/public/images/map/taxi_green.png'}";
		var image2 = "@{'/public/images/map/taxi_magenta.png'}";
		var image3 = "@{'/public/images/map/taxi_orange.png'}";
		var image4 = "@{'/public/images/map/taxi_red.png'}";
		var image5 = "@{'/public/images/map/taxi_yellow.png'}";
		var yellowUser = "@{'/public/images/map/user_yellow.png'}";
		var orangeUser = "@{'/public/images/map/user_orange.png'}";
		var redUser = "@{'/public/images/map/user_red.png'}";
		
		var clickAble = true;
		////
		
		
		function initialize() {
			
			//random  coordinates to initialize map
			var latlng = new google.maps.LatLng(lat, lng);
			//setting map's parameters
			var mapOptions = {

				zoom: 12,

				mapTypeId: google.maps.MapTypeId.ROADMAP,

				center: latlng

			};

				map = new google.maps.Map(document.getElementById("map_canvas"),

			    mapOptions);
		
		}
	//This method add marker of provider to map and declare himself at system 
	function createProv(){
		lat = $('#la').val();
		lng = $('#lo').val();
                                var login = $('#login').val();
                                var password = $('#password').val();
		initialize();
		if((lng!='')&&(lat!='')){
			$.ajax({
		          url: signin,
		          data: {pLat:lat,pLong:lng,login:login,password:password},
		          success: function(events) {
		              $(events).each(function() {
                                                      
                          provId = Number(this);
                          if (provId != -1){
                                  callDeclare(provId);
                                  putMarker('you',0,lat,lng,greenTaxi);
                                  document.getElementById('crtProvM').style.display = 'none';
                          }
                          else{
                                  alert("The login or password you entered is incorrect");
                          }

                      })
					},
		          dataType: 'json'
		    });
		    return true;
		}
		alert("You don't write coordinates of provider");	

	}
	// function makeDeclare(){
	// 	$.ajax({
	// 	          url: declare,
	// 	          data: {pLat:lat,pLong:lng},
	// 	          success: function(events) {
	// 	              manager();
	// 	          },
	// 	          dataType: 'json'
	// 	    });
	// }
	// This function used for get and manage new events from server
	function manager(){
		
		var getEvents = function() {
              $.ajax({
                  url: waitEvents,
                  data: {lastReceived: lastReceived, provId:provId},
                  success: function(events) {
                  $(events).each(function() {
                          lastReceived = this.id;
                          eventManager(this.data);
                      })
                      getEvents()
                  },
                  dataType: 'json'
              });
          }
          getEvents();
          //manage events from server
          function eventManager(event){

          	  if(event.status=="u_requested"){
	              userId = event.userId;
				  putMarker("requested",userId, event.u_lat, event.u_long, yellowUser);
			  };
	          if(event.status=="u_confirmed"){
	              alert("OK, user wait you");
	              for(i in markers){
	              	if(markers[i].id == event.userId){
	              		userMarker = markers[i];
	              	}
	              }
	              document.getElementById("startTrip").style.display = "inline";
	          };
	          if(event.status=="u_canceled"){
	              alert("Sorry but this user canceled request for taxi");
	              clickAble = true;
                              var flag = 0;
	              for(i in markers){
	                	if(markers[i].id == event.userId){
	                		markers[i].setMap(null);
	                	}
	                	else{
	                		markers[i].setVisible(true);
                                                                if(markers[i].map != null){
                                                                        flag++;
                                                                }
			}
	                }
                                if (flag == 0){
                                        $.ajax({
		          url: declare,
		          data: {provId:provId,pLat:lat,pLong:lng},
		          success: function(events) {
		             // manager();
		          },
		          dataType: 'json'
		    });
                                }
	              
	          };
	          if(event.status == "p_acceptedCanceled")
	          {
	        	  	alert("You don't accept request from user with id " + event.userId);
	                clickAble = true;
                                var flag = 0;
	                for(i in markers){
	                        if(markers[i].id == event.userId){
	                                markers[i].setMap(null);
	                        }
	                        else{
	                                markers[i].setVisible(true);
                                                if(markers[i].map != null){
                                                        flag++;
                                                }
	                        }
	                }
                                if (flag == 0){
                                        $.ajax({
		          url: declare,
		          data: {provId:provId,pLat:lat,pLong:lng},
		          success: function(events) {
		             // manager();
		          },
		          dataType: 'json'
		    });
                                }
	          }
          }  	
	}

	function startTrip(){
		userMarker.setIcon(redUser);
		document.getElementById("startTrip").style.display = "none";
		document.getElementById("endTrip").style.display = "inline";
		$.post(lockUser,{userId:userId,provId:provId});
	};

	function endTrip(){
		 document.getElementById("endTrip").style.display = "none";
		 document.getElementById("provMenu").style.display = "inline";
		 $.post(reached,{userId:userId,provId:provId});
	};
	
	function callDeclare(){
			
			$.ajax({
		          url: declare,
		          data: {provId:provId,pLat:lat,pLong:lng},
		          success: function(events) {
		              manager();
		          },
		          dataType: 'json'
		    });
		}

	function newTrip(){
		document.getElementById("provMenu").style.display = "none";
		$.ajax({
		          url: end,
		          data: {provId:provId},
		          success: function(events) {
		              callDeclare();
		          },
		          dataType: 'json'
		    });
		provMarker.setMap(null);
		userMarker.setMap(null);
		for(i in markers){
			markers[i].setMap(null);
		}
		lastReceived = 0;
		clickAble = true;
		putMarker('you',0,lat,lng,greenTaxi);
	}

	//call when provider exit from system
	function endWork(){
		document.getElementById("provMenu").style = "none";
		$.get(end,{provId:provId});	
		$.post(exit,{provId:provId});
		alert("Good bye!!!");
		document.location.reload();	
	}

	//with two parameters (latitude & longitude) this function finds you on the map and puts a marker in the exact position you set.
    function putMarker(title, id, lat, lng,image) {
      //take parameters from edit box
		//lat = document.getElementById("la").value
        //lng = document.getElementById("lo").value
			yourlocation = new google.maps.LatLng(lat, lng);
			//set map's center on the user's location
			map.setCenter(yourlocation);

			
			//marker's options
			marker = new google.maps.Marker({
			
				icon: image,
				
				map:map,

				draggable:true,

				animation: google.maps.Animation.DROP,

				position: new google.maps.LatLng(lat, lng),

				id: id,

				title: title

			});
			
			
			if(title != 'you'){
				markers.push(marker);
				google.maps.event.addListener(marker, "click", function() {
					if(clickAble==true){
						var inf = prompt("Enter information for client (for instead, when you com to him)","");
                        var time = prompt("Enter timeout please","100");
                        userId = this.id;
						this.setIcon(orangeUser);
						//userMarker = this;
						for(i in markers){
							if(markers[i].id != userId){
		                		markers[i].setVisible(false);
		                	}
		                }
						$.post(provAccept,{inf:inf,time:time,userId:userId,provId:provId});
						clickAble = false;	
					}
					else{
						alert("You already choose client!");
					}
					
				});	
			}
			else{
				provMarker = marker;
			}
			
			
	}
	//find user's geolocation and set the center of the map on his cordinates
	function gotPosition(pos)  {
	
		lati = pos.coords.latitude;
        lngi = pos.coords.longitude;
			yourlocation = new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude);
			map.setCenter(yourlocation);
			
			
		}
		//this function puts some markers on the map (one for user and the others for taxis)
		function setTaxiPosition() {
		
		document.getElementById("lo").value = lngi;
		document.getElementById("la").value = lati;
		map.setCenter(yourlocation);
			
			//marker's options
			marker = new google.maps.Marker({

				map:map,
				
				icon:'user_blue.png',

				draggable:true,
				
				title:"You're here",

				animation: google.maps.Animation.DROP,

				position: yourlocation

			});
			
			
			
			//Json parsing and extraction of needed paramiters
			var contact = JSON.parse(jsonString);
			//this for-cycle will add markers for every taxi available at the moment of the request
			for(i=0; i < contact.provsList.length; i++){
			//extract userId
			var title = contact.provsList[i].userId;
			//extract coordinates
			var ps = new google.maps.LatLng(contact.provsList[i].PLat, contact.provsList[i].PLong);
			//set the marker for the position
			var marks = new google.maps.Marker({
			
			title: "Taxi n."+title+"",
			position: ps, 
			draggable:true,
			animation: google.maps.Animation.DROP,
			map: map, 
			//the taxi color is defined by its availability. See status diagram flow
			icon: 'taxi_green.png', 
			flat: true
				
				}
			);
			marks[i] = marker; 
			}
			
			
			}
			
			//errors management
			function errorGettingPosition(err) {

			if(err.code == 1) {

				alert("Geolocation not allowed");

			} else if(err.code == 2) {

				alert("Position not available");

			} else if(err.code == 3) {

				alert("Timeout");

			} else {

				alert("ERROR:" + err.message);

			}

		}

	//find current position on execution
	// navigator.geolocation.getCurrentPosition(

	// 	gotPosition,

	// 	errorGettingPosition,

	// 	{'enableHighAccuracy':true,'timeout':10000,'maximumAge':0}

	// );
</script>

</font>
</head>

<body onload="initialize()" bgcolor="green">
<table align="center">
<tr><td>		
</font>
	</div>
<br><br><br><br>
	<div  id="map_canvas" style="height: 400px; width: 600px; float: center;"></div>


</td><td><div align="left">
	<div id="crtProvM">
		Latitudine: &nbsp&nbsp&nbsp<input type="text" name="la" id="la" value="48.45" /><br/>
  		Longitudine: <input type="text" name="lo" id="lo" value="34.983333" /><br/>
                                Login:&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp<input type="text" name="login" id="login" value="${login}" /><br/>
                                Password:&nbsp&nbsp&nbsp&nbsp<input type="text" name="password" id="password" value="${password}" /><br/>
  		<input type="button" value="Sign in" onclick="createProv()"/><br/>
                                <input type="button" value="Registration" onclick="location.href='@{Application.provRegistration()}'"/><br/>
	</div>
  	
  	<div id="provMenu">
  		<input type="button" id="declare" value="Declare" onclick="newTrip()"/><br/>
  		<input type="button" id="endWork" value="End Work" onclick="endWork()"/><br/>
  	</div>

  <input type="button" id="startTrip" value="Start trip" onclick="startTrip()"/><br/>
  <input type="button" id="endTrip" value="End trip" onclick="endTrip()"/><br/>
  
  
</td></tr>

</table>
</body></div></html>